package me.zingon.doc.util;

import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * Created by zhidi on 2018-3-26.
 */
public class HttpUtil {

    private static Logger logger= LoggerFactory.getLogger(HttpUtil.class);

    private static OkHttpClient okHttpClient=new OkHttpClient.Builder().readTimeout(50L, TimeUnit.SECONDS).build();

    public static String postJson(String url, String json){
        RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8"), json);
        return post(url,requestBody);
    }

    public static String postForm(String url, Map<String,String> params){
        FormBody.Builder formBuilder= new FormBody.Builder();
        if(params!=null&&params.size()>0) {
            Set<Map.Entry<String, String>> set = params.entrySet();
            for (Map.Entry<String, String> e : set) {
                formBuilder.add(e.getKey(), e.getValue());
            }
        }
        return post(url,formBuilder.build());
    }

    private static String post(String url, RequestBody body) {
        logger.info("发送post：{}",url);
        Request request=new Request.Builder()
                .url(url)
                .post(body)
                .build();
        //出现异常就尝试3次
        int count=0;
        while(count<3) {
            try {
                Response response = okHttpClient.newCall(request).execute();
                String result=response.body().string();
                logger.info("post返回：{}",result);
                return result;
            } catch (IOException e) {
                count++;
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
                e.printStackTrace();
            }
        }
        return "failed";
    }

    public static String get(String url, Map<String, String> params){
        logger.info("发送get：{}",url);
        if(params!=null&&params.size()>0) {
            StringBuilder sb=new StringBuilder(url+"?");
            Set<Map.Entry<String, String>> set = params.entrySet();
            for (Map.Entry<String, String> e : set) {
                sb.append(e.getKey()).append("=").append(e.getValue()).append("&");
            }
            String temp=sb.toString();
            url=temp.substring(0,temp.length()-1);
        }
        Request request = new Request.Builder()
                .url(url)
                .build();

        try {
            Response response = okHttpClient.newCall(request).execute();
            String result=response.body().string();
            logger.info("get返回：{}",result);
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "failed";
    }
}
